package servlet;

import entity.User;
import service.UserService;
import service.UserServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = "/user_login")
public class User_loginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        response.setContentType("text/html;charset=UTF-8");
        UserService userService = new UserServiceImpl();
        User user = new User();
        String username = request.getParameter("ue");
        String password = request.getParameter("password");
        try {
            user = userService.login(username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        PrintWriter out = response.getWriter();
        if (user != null){
            session.setAttribute("user",user);
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }else{
            out.print("<script>alert('登录失败');history.back();</script>");
        }
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }
}
